package com.tang.script.functions;

import cn.hutool.core.io.IoUtil;
import com.tang.script.exceptions.ScriptException;
import groovy.lang.GroovyShell;
import lombok.Getter;
import lombok.Setter;

import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.Objects;

@Getter
@Setter
public class DefaultFunctionLoader implements FunctionLoader {
    GroovyShell groovyShell = new GroovyShell();

    @Override
    public synchronized Object loadFunction(String functionName) {
        String functionText = readText(functionName);
        Class evaluate = (Class) groovyShell.run(functionText, functionName, new LinkedList<>());
        try {
            return evaluate.newInstance();
        } catch (Exception e) {
            throw new ScriptException("加载脚本失败: " + functionName, e);
        }
    }

    public String readText(String functionName) {
        URL resource = DefaultFunctionLoader.class.getClassLoader().getResource("script/functions/" + functionName + ".groovy");
        if (Objects.isNull(resource)) {
            throw new ScriptException("找不到函数: " + functionName);
        }
        try (InputStream inputStream = resource.openStream()) {
            String functionText = IoUtil.read(inputStream, Charset.defaultCharset());
            return functionText += "\n" +
                    functionName;

        } catch (Exception e) {
            throw new ScriptException(e);
        }
    }
}
